#include "threadPool.h"
#include "worker.h"
#include "cmdFunc.h"

train_t train;

int tidArrInit(tidArr_t *ptidArr,int workerNum)//初始化子线程信息结构体
{
    ptidArr->arr = (pthread_t *)calloc(workerNum,sizeof(pthread_t));
    ptidArr->workerNum = workerNum;
    return 0;
}

int makeWorker(threadPool_t *pthreadpool)//创建工人进程
{
    for(int i = 0;i < pthreadpool->tidArr.workerNum;i++)
    {
        pthread_create(&pthreadpool->tidArr.arr[i],NULL,threadFunc,pthreadpool);
    }
    return 0;
}

void *threadFunc(void *arg)//子线程函数
{
    threadPool_t * pthreadpool = (threadPool_t *)arg;
    cwd_t **ppcwd = (cwd_t**)calloc(1, sizeof(cwd_t*));
    *ppcwd = NULL;
    while(1)
    {
        pthread_mutex_lock(&pthreadpool->mutex);
        int netfd;
        cmd_t cmd;
        while(pthreadpool->exitFlag == 0 && pthreadpool->taskQueue.queueSize <= 0)
        {
            pthread_cond_wait(&pthreadpool->cond,&pthreadpool->mutex);
        }
        if(pthreadpool->exitFlag == 1)
        {
            pthread_mutex_unlock(&pthreadpool->mutex);
            pthread_exit(NULL);
        }
        netfd = pthreadpool->taskQueue.pFront->netfd;
        //接收cmd
        recv(netfd,&train.length,sizeof(train.length),0);
        recv(netfd,train.data,train.length,0);
        memcpy(&cmd,&train.data,sizeof(cmd_t)); 
        deQueue(&pthreadpool->taskQueue);
        pthread_mutex_unlock(&pthreadpool->mutex);

        cmdServerHandler(netfd, ppcwd, &cmd);
    }

}
